package com.sanji.springmvc.messageconverter;

import com.sanji.springmvc.domain.DemoObj;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by joe on 17-4-23.
 */
public class MyMessageConverter extends AbstractHttpMessageConverter<DemoObj> {

  //2.自定义的媒体类型
  public MyMessageConverter() {
    super(new MediaType("application", "x-wisely", Charset.forName("UTF-8")));
    System.out.println("00000000");
  }

    //3.重写readInternal方法,处理请求数据.代码表明我们处理由“-”隔开数据，并转成DemoObj的对象
    @Override
    protected DemoObj readInternal(Class<? extends DemoObj> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
      System.out.println("11111111");
      String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
      String[] tempArr = temp.split("-");
      return new DemoObj(new Long(tempArr[0]), tempArr[1]);
    }

  //4.表明HttpMessageConverter只处理DemoObj这个类
  @Override
  protected boolean supports(Class<?> clazz) {
    System.out.println("222222");
    return DemoObj.class.isAssignableFrom(clazz);
  }

  //5.重写writeInternal，处理如何输出数据到response。此例中，原样输出，前面加上“hello： ”
  @Override
  protected void writeInternal(DemoObj demoObj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    String out = "hello: " + demoObj.getId() + "-" + demoObj.getName();
    outputMessage.getBody().write(out.getBytes());
  }
}
